﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;

namespace WebApplication.Files
{
    public partial class Upload : System.Web.UI.Page
    {
        /// <summary>
        /// 计算文件的MD5值
        /// </summary>
        /// <param name="filepath">文件全路径</param>
        /// <returns></returns>
        public string MD5Value(HttpPostedFile file)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] md5ch;
            md5ch = md5.ComputeHash(file.InputStream);
            md5.Clear();
            string strMd5 = "";
            for (int i = 0; i < md5ch.Length - 1; i++)
            {
                strMd5 += md5ch[i].ToString("x").PadLeft(2, '0');
            }
            return strMd5;
        }
        /// <summary>
        /// 输出json到页面
        /// </summary>
        /// <param name="o"></param>
        private void WriteJson(Object o)
        {
            Response.ContentType = "application/json; charset=utf-8";
            var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string Json = javaScriptSerializer.Serialize(o);
            Response.Write(Json);
        }

        private long getTimeStamp()
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            long timeStamp = (long)(DateTime.Now - startTime).TotalSeconds; // 相差秒数
            return timeStamp;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string saveFile(HttpPostedFile file)
        {

            string uploadPath = ConfigurationManager.AppSettings["UploadPath"];
            string filePostFixName = file.FileName.Split('.')[1];
            string fileMD5Name = MD5Value(file);
            //long timeStamp = getTimeStamp();
            //string fileName = string.Format("{0}_{1}", timeStamp, fileMD5Name);
            string fileName = fileMD5Name;
            string savePath = "~" + uploadPath + fileName + "." + filePostFixName;
            string filePath = Server.MapPath(savePath);
            file.SaveAs(filePath);
            return savePath;
        }

        /// <summary>
        /// 判断上传目录是否存在，不存在就创建
        /// </summary>
        private void createDir()
        {
            string uploadPath = ConfigurationManager.AppSettings["UploadPath"];
            string path = Server.MapPath("~" + uploadPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            createDir();
            if (Request.Files.Count > 1)
            {
                List<string> urls = new List<string>();
                foreach (string key in Request.Files.Keys)
                {
                    string path = saveFile(Request.Files[key]);
                    urls.Add(path);
                }
                WriteJson(new { url = urls });
            }
            else
            {
                string path = saveFile(Request.Files[0]);
                WriteJson(new { url = path });
            }

        }
    }
}